var express = require('express');
var router = express.Router();
var db = require('../../mysqldb');
var fs = require('fs');
module.exports = function (app) {
    app.use('/admin/news', router);
};

//添加新闻
router.post('/addlist',(req, res, next) => {
  db(`INSERT INTO News VALUES (null,'${req.body.Title}','${req.body.Sumary}','${req.body.Source}','${req.body.Link}','${req.body.UpdataTime}','${req.body.Content}','${req.body.Picture}',${req.body.Sort},${req.body.Type},${req.body.IsDisplay},${req.body.IsIndex},${req.body.FrId},${req.body.SecondFrId},'${new Date()}','${req.body.SecondName}',0)`,(err,rows)=>{
      if(err){
        console.log(err)
        res.send({ret:false})
      }
      res.send({ret:true})
    });
  })

//修改新闻
router.post('/update', (req, res, next) => {
  var newdata = req.body.UpdataTime.toString()
  if(newdata.split('T').length>1){
    newdata= newdata.split('T')[0]
  }
  db(`UPDATE News SET Title='${req.body.Title}',Sumary='${req.body.Sumary}',Source='${req.body.Source}',Link='${req.body.Link}',UpdataTime='${newdata}',Content='${req.body.Content}',Picture='${req.body.Picture}',Sort=${req.body.Sort},Type=${req.body.Type},IsDisplay=${req.body.IsDisplay},IsIndex=${req.body.IsIndex},FrId=${req.body.FrId},SecondFrId=${req.body.SecondFrId},SecondName='${req.body.SecondName}' where id='${req.body.id}'`,(err,rows)=>{
      if(err){
        res.send({ret:false})
      }
      res.send({ret:true})
    });
  })

//显示全部新闻，带分页
router.post('/show', async (req, res, next) => { 
    db(`select * from News where FrId='${req.body.FrId}' order by Sort desc`,(err,rows)=>{
      var offset= req.body.offset?req.body.offset:0;
      var limit = req.body.limit?req.body.limit:10;
      if(err){
        res.send({ret:false})
      }
        res.send({
          ret:true,
          total:rows.length,
          data:rows.splice(offset,limit)
        })
    });
})

//显示单个新闻内容
router.post('/showone',function(req,res,next){
    db(`select * from News where id=${req.body.id}`,(err,rows)=>{
      if(err){
        res.send({ret:false})
      }
      res.send({ret:true,data:rows[0]})
    });
})

//删除新闻
router.post('/del', async (req, res, next) => {
    db(`DELETE  from News where id='${req.body.id}'`,(err,rows)=>{
      if(err){
        res.send({ret:false})
      }
      res.send({ret:true})
    });
  })

